﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;

namespace Bootstrap_Project.Web
{
    /// <summary>
    /// ported from OSF framework with minimal changes
    /// </summary>
    public class Serializer
    {
        public static string Serialize<T>(T objectToSerialize) where T : new()
        {
            DataContractSerializer serializer = new DataContractSerializer(objectToSerialize.GetType());
            return Serialize(objectToSerialize, serializer);
        }

        public static string Serialize<T>(T objectToSerialize, DataContractSerializer serializer) where T : new()
        {
            StringBuilder stringBuilder = new StringBuilder();
            using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder))
            {
                serializer.WriteObject(xmlWriter, objectToSerialize);
                xmlWriter.Flush();
            }
            return stringBuilder.ToString();
        }

        internal static T Deserialize<T>(string xml)
        {
            return (T)Deserialize(xml, typeof(T));
        }

        internal static object Deserialize(string xml, Type suggestedType)
        {
            if (string.IsNullOrEmpty(xml)) return null;
            using (StringReader stringReader = new StringReader(xml))
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreWhitespace = true;
                settings.IgnoreComments = true;
                using (XmlReader xmlReader = XmlReader.Create(stringReader, settings))
                {
                    DataContractSerializer serializer = new DataContractSerializer(suggestedType);

                    return serializer.ReadObject(xmlReader);
                }
            }
        }
    }
}
